package com.miplus.ccrm.workflow.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.workflow.model.common.DeleteRequest;
import com.miplus.ccrm.workflow.model.dto.knowledge.MatchDTO;
import com.miplus.ccrm.workflow.model.dto.knowledge.MatchRuleCreateDTO;
import com.miplus.ccrm.workflow.model.dto.knowledge.MatchRuleUpdateDTO;
import com.miplus.ccrm.workflow.model.po.WorkflowKnowledgeQuestion;
import com.miplus.ccrm.workflow.model.po.WorkflowKnowledgeQuestionRule;
import com.miplus.ccrm.workflow.model.vo.MatchRuleVO;
import com.miplus.ccrm.workflow.model.vo.MatchVO;
import com.miplus.ccrm.workflow.service.WorkflowKnowledgeQuestionRuleService;
import com.miplus.ccrm.workflow.mapper.WorkflowKnowledgeQuestionRuleMapper;
import com.miplus.ccrm.workflow.service.WorkflowKnowledgeQuestionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author feixiang
 * @description 针对表【workflow_knowledge_question_rule(知识库问题匹配规则表（存储问题的正则/关键词，支持任意数量）)】的数据库操作Service实现
 * @createDate 2025-11-05 14:32:01
 */
@Service
public class WorkflowKnowledgeQuestionRuleServiceImpl extends MPJBaseServiceImpl<WorkflowKnowledgeQuestionRuleMapper, WorkflowKnowledgeQuestionRule>
        implements WorkflowKnowledgeQuestionRuleService {

    @Resource
    private WorkflowKnowledgeQuestionService questionService;

    @Override
    public CmdResVo cereateMatchRule(MatchRuleCreateDTO ruleDTO) {
        //请求不能为空
        if (ruleDTO == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        //注意同一个问题id，同一个规则类型，规则内容不能重复
        //查询是否存在相同的规则
        WorkflowKnowledgeQuestionRule existingRule = this.lambdaQuery()
                .eq(WorkflowKnowledgeQuestionRule::getQuestionId, ruleDTO.getQuestionId())
                .eq(WorkflowKnowledgeQuestionRule::getRuleType, ruleDTO.getRuleType())
                .eq(WorkflowKnowledgeQuestionRule::getRuleContent, ruleDTO.getRuleContent())
                .one();
        if (existingRule != null) {
            throw new ServiceException(50016, "规则已存在");
        }
        WorkflowKnowledgeQuestionRule rule = new WorkflowKnowledgeQuestionRule();
        rule.setQuestionId(ruleDTO.getQuestionId());
        rule.setRuleType(ruleDTO.getRuleType());
        rule.setRuleContent(ruleDTO.getRuleContent());
        rule.setStatus(1);
        rule.setIsDeleted(0);
        boolean save = this.save(rule);
        if (!save) {
            throw new ServiceException(EnumRCode.DBErr.value, EnumRCode.DBErr.name);
        }
        return new CmdResVo(1, rule.getPid().toString());
    }

    @Override
    public CmdResVo updateMatchRule(MatchRuleUpdateDTO ruleDTO) {
        //请求不能为空
        if (ruleDTO == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        //规则id不能为空
        if (ruleDTO.getPid() == null || ruleDTO.getRuleType() == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        //查找记录
        WorkflowKnowledgeQuestionRule rule = this.getById(ruleDTO.getPid());
        if (rule == null) {
            throw new ServiceException(EnumRCode.DataNotExist.value, EnumRCode.DataNotExist.name);
        }
        //更新记录
        rule.setRuleType(ruleDTO.getRuleType());
        rule.setRuleContent(ruleDTO.getRuleContent());
        rule.setStatus(ruleDTO.getStatus());
        boolean update = this.updateById(rule);
        if (!update) {
            throw new ServiceException(EnumRCode.DBErr.value, EnumRCode.DBErr.name);
        }
        return new CmdResVo(1, rule.getPid().toString());
    }

    @Override
    public CmdResVo deleteMatchRule(DeleteRequest deleteRequest) {
        //请求不能为空
        if (deleteRequest == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        //规则id不能为空
        if (deleteRequest.getId() == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        //查找记录
        WorkflowKnowledgeQuestionRule rule = this.getById(deleteRequest.getId());
        if (rule == null) {
            throw new ServiceException(EnumRCode.DataNotExist.value, EnumRCode.DataNotExist.name);
        }
        //删除
        boolean delete = this.removeById(rule);
        if (!delete) {
            throw new ServiceException(EnumRCode.DBErr.value, EnumRCode.DBErr.name);
        }
        return new CmdResVo(1, rule.getPid().toString());
    }

    @Override
    public List<MatchRuleVO> getMatchRuleList(Long questionId) {
        if (questionId == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }

        // 查询问题表判断问题是否存在
        WorkflowKnowledgeQuestion question = questionService.getById(questionId);
        if (question == null) {
            throw new ServiceException(EnumRCode.DataNotExist.value, EnumRCode.DataNotExist.name);
        }
        // 查询该问题对应的有效规则  //todo 使用逻辑删除
        List<WorkflowKnowledgeQuestionRule> rules = this.lambdaQuery()
                .eq(WorkflowKnowledgeQuestionRule::getQuestionId, questionId)
                .list();
        return rules.stream()
                .map(rule -> {
                    // 实例化VO并设置字段（根据实际VO构造方法调整）
                    MatchRuleVO vo = new MatchRuleVO();
                    vo.setPid(rule.getPid());
                    vo.setQuestionId(rule.getQuestionId());
                    vo.setRuleType(rule.getRuleType());
                    vo.setRuleContent(rule.getRuleContent());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public MatchVO matchKnowledgeQuestion(MatchDTO matchDTO) {
        // 参数校验
        if (matchDTO == null || matchDTO.getKid() == null || matchDTO.getQuestionContent() == null) {
            throw new ServiceException(EnumRCode.ArgFormatErr.value, EnumRCode.ArgFormatErr.name);
        }
        MatchVO matchVO = new MatchVO();
        matchVO.setQuestion(matchDTO.getQuestionContent());
        // 遍历知识库集合，查询每个知识库下的所有启用问题
        List<WorkflowKnowledgeQuestion> questions = new ArrayList<>();
        for (Long kbId : matchDTO.getKid()) {
            questions.addAll(questionService.lambdaQuery()
                    .eq(WorkflowKnowledgeQuestion::getKbId, kbId)
                    .eq(WorkflowKnowledgeQuestion::getStatus, 1)
                    .list());
        }
        // 遍历所有问题，查找匹配的规则
        for (WorkflowKnowledgeQuestion question : questions) {
            // 查询该问题下的所有启用的规则，按优先级排序
            List<WorkflowKnowledgeQuestionRule> rules = this.lambdaQuery()
                    .eq(WorkflowKnowledgeQuestionRule::getQuestionId, question.getPid())
                    .eq(WorkflowKnowledgeQuestionRule::getStatus, 1)
                    .list();
            // 优先使用正则匹配
            for (WorkflowKnowledgeQuestionRule rule : rules) {
                // 跳过非正则表达式的规则
                if (rule.getRuleType() != 1) {
                    continue;
                }
                try {
                    if (matchDTO.getQuestionContent().matches(rule.getRuleContent())) {
                        // 匹配成功，返回问题内容
                        matchVO.setAnswer(question.getContent());
                        return matchVO;
                    }
                } catch (Exception e) {
                    // 正则表达式格式错误，跳过该规则
                    continue;
                }
            }
            // 再使用关键词匹配
            for (WorkflowKnowledgeQuestionRule rule : rules) {
                // 跳过非关键词的规则
                if (rule.getRuleType() != 2) {
                    continue;
                }
                if (matchDTO.getQuestionContent().contains(rule.getRuleContent())) {
                    // 匹配成功，返回问题内容
                    matchVO.setAnswer(question.getContent());
                    return matchVO;
                }
            }
        }
        // 没有匹配到规则，返回默认提示信息
        matchVO.setAnswer("未匹配到相关问题");
        return matchVO;
    }
}
